package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import com.badibadi.activity.AfterLandingActivity;
import com.badibadi.activity.LogReadingActivity;
import com.badibadi.infos.MyRecordListInfos;
import com.badibadi.infos.Record_List_Model;
import com.badibadi.infos.Results;
import com.badibadi.mytools.BitmapHelp;
import com.badibadi.mytools.CommonUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyRecordList0Fragment extends BaseFragment implements
		IXListViewListener {
	List<Record_List_Model> list;
	static MyRecordList0Fragment fragment;
	private XListView mListView;
	// private Handler mHandler;
	private Results results;
	private Results results3;
	private String type = null;
	private MyRecordList0FragmentAdapter fragmentAdapter;
	private List<Record_List_Model> record_List_Models;
	private DisplayImageOptions options;
	private int Page;
	private SetGetView setGetView;
	int pos_ = -1;
	private int pos = 0;
	private String uid;// 用户id
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_net_error));
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:
				try {
					Utils.ExitPrgress(getActivity());

					record_List_Models.addAll(list);
					fragmentAdapter.notifyDataSetChanged();
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xa10));
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 5:

				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(), results3.getRetmsg());
					if (results3.isRet()) {
						int d = Integer.valueOf(record_List_Models.get(pos)
								.getVote());
						record_List_Models.get(pos).setVote(++d + "");
						record_List_Models.get(pos).setVoted("1");
						fragmentAdapter.notifyDataSetChanged();
					}
					// else {
					// int d = Integer.valueOf(record_List_Models.get(pos)
					// .getVote());
					// if (d > 0) {
					// record_List_Models.get(pos).setVote(--d + "");
					// } else {
					// record_List_Models.get(pos).setVote(0 + "");
					// }
					// fragmentAdapter.notifyDataSetChanged();
					// }
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 9://

				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xb12));
				} catch (Exception e) {

				}
				break;
			case 10:// 收藏成功

				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(
							getActivity(),
							getResources().getString(
									R.string.wx_shoucang_success));

					if (pos_ != -1) {

						// mList.get(pos_).setIs_collect("1");

						record_List_Models.get(pos_).setCollect(
								""
										+ (Integer.parseInt(record_List_Models
												.get(pos_).getCollect()) + 1));
						// user_trends.get(pos_).setIs_collected(1);
						// user_trends.get(pos_).setCollect(""+(Integer.parseInt((user_trends.get(pos_).getCollect()))+1));
						fragmentAdapter.notifyDataSetChanged();
						pos_ = -1;
					}
				} catch (Exception e) {

				}
				break;
			case 11://

				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.wx_txt_70));
				} catch (Exception e) {

				}
				break;
			case 12:
				try {
					Page = 1;
					record_List_Models.clear();
					All_record(Page);
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// mHandler = new Handler();
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater
				.inflate(R.layout.fragment_myrecordlist_me_01, null);
		Page = 0;
		uid = Utils.getUid(getActivity());
		type = getArguments().getString("type", "new");
		record_List_Models = new ArrayList<Record_List_Model>();
		mListView = (XListView) view
				.findViewById(R.id.fragment_myrecord_list_me_XlistView);
		fragmentAdapter = new MyRecordList0FragmentAdapter(getActivity());
		mListView.setXListViewListener(this);
		mListView.setPullLoadEnable(true);
		mListView.setPullRefreshEnable(true);
		mListView.setAdapter(fragmentAdapter);
		mListView.startLoadMore();
		return view;
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (Constants.is_shuaxin) {
			handler.sendEmptyMessageDelayed(12, 700);
			Constants.is_shuaxin = false;
		}
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	protected void onLoad() {
		// TODO Auto-generated method stub
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime(""+getResources().getString(R.string.ganggang));
	}

	public static MyRecordList0Fragment getInstance() {
		if (fragment == null) {
			return new MyRecordList0Fragment();
		}
		return fragment;
	}

	public void All_record(final int page) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				list = new ArrayList<Record_List_Model>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", type);
				map.put("page", page);
				map.put("pageNum", 10);
				if (uid != null && !uid.equals("")) {
					map.put("uid", uid);
				}
				String rcontent = Utils.sendRequest(map, Constants.BadiUrl
						+ "all_record");
//				   
//						+ "      " + map.toString());
				if (rcontent != null) {
//					   (rcontent);
//					   
					results = Utils.checkResult_NNN(getActivity(), rcontent);
					if (results != null && !results.getRetmsg().equals("null")) {
						try {
							list = JSONUtils.getListByJsonString(
									results.getRetmsg(),
									Record_List_Model.class);
							handler.sendEmptyMessage(2);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						handler.sendEmptyMessage(3);
					}
				} else {
					if (page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	public class MyRecordList0FragmentAdapter extends BaseAdapter {
		protected static final String TAG = "MyRecordList0FragmentAdapter";
		private Context context;

		public MyRecordList0FragmentAdapter(Context ct) {
			context = ct;

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return record_List_Models.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return record_List_Models.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// TODO Auto-generated method stub
			// if(convertView==null)//缓存
			// LayoutInflater layoutInflater = (LayoutInflater) context
			// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);// 布局填充服务
			if (setGetView != null) {
				convertView = setGetView.setGetView(position, convertView,
						parent);
			} else {
				LayoutInflater inflater = LayoutInflater.from(context);
				convertView = inflater.inflate(
						R.layout.fragment_myrecordlist0_import_layout, null);
				// 地址
				TextView address = (TextView) convertView
						.findViewById(R.id.fragment_myrl_import_adress_textview);
				// 开始时间
				TextView startTime = (TextView) convertView
						.findViewById(R.id.f_m_i_l_starttime);
				// 结束时间
				TextView overTime = (TextView) convertView
						.findViewById(R.id.f_m_i_l_overtime);
				// 头像
				ImageView headimg = (ImageView) convertView
						.findViewById(R.id.f_m_i_l_touxiang);
				// 背景图
				ImageView background_img = (ImageView) convertView
						.findViewById(R.id.fragment_myrl_import_background_img);
				// 名字
				TextView myname = (TextView) convertView
						.findViewById(R.id.f_m_i_l_name);
				// 投票数量
				TextView votenumber = (TextView) convertView
						.findViewById(R.id.f_m_i_l_vote_number);
				// 观看数量
				TextView seenumber = (TextView) convertView
						.findViewById(R.id.f_m_i_l_see);
				// 评论数量
				TextView pinlun = (TextView) convertView
						.findViewById(R.id.f_m_i_l_say);
				// 收藏(心的标识)
				TextView collection = (TextView) convertView
						.findViewById(R.id.f_m_i_l_xin);
				// 投票
				Button f_m_i_l_toupiao = (Button) convertView
						.findViewById(R.id.f_m_i_l_toupiao);
				address.setText(record_List_Models.get(position).getName());
				startTime.setText(record_List_Models.get(position)
						.getStart_time());
				overTime.setText(record_List_Models.get(position).getEnd_time());
				votenumber.setText(record_List_Models.get(position).getVote());
				seenumber.setText(record_List_Models.get(position).getView());
				pinlun.setText(record_List_Models.get(position).getDiscuss());
				collection.setText(record_List_Models.get(position)
						.getCollect());
				ImageLoader.getInstance().displayImage(
						Constants.BadiDownImgUrl
								+ record_List_Models.get(position).getHead()
								+ Constants.appPhoto4img, headimg, options);
				// ImageLoader.getInstance().displayImage(
				// Constants.BadiDownImgUrl
				// + record_List_Models.get(position).getImage()
				// + Constants.Appactivitycover, background_img,
				// options);
				new BitmapHelp().displayImage(
						getActivity(),
						background_img,
						Constants.BadiDownImgUrl
								+ record_List_Models.get(position).getImage()
								+ Constants.Appactivitycover);

				// 收藏按钮
				ImageView iv_collect = (ImageView) convertView
						.findViewById(R.id.iv_collect);

				iv_collect.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						if (!Utils.getUid(getActivity()).equals("")) {
						pos_ = position;
						collect("0", record_List_Models.get(position).getUid(),
								record_List_Models.get(position).getRid(),
								"record");
						}else {
							Utils.showMessage(
									getActivity(),
									getResources().getString(
											R.string.l_xb10));
						}
					}
				});

				background_img.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						/*if (!Utils.getUid(context).equals("")) {*/
							Intent intent = new Intent(context,
									LogReadingActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							if (record_List_Models.get(position).getId() != null) {
								intent.putExtra("rid",
										record_List_Models.get(position)
												.getId());
							} else {
								intent.putExtra("rid",
										record_List_Models.get(position)
												.getRid());
							}
							context.startActivity(intent);
						} /*else {
							Toast.makeText(context,
									getResources().getString(R.string.l_xb10),
									0).show();
						}*/
						// Toast.makeText(
						// context,
						// "查看记录"
						// + record_List_Models.get(position)
						// .getTitle(), 0).show();

					/*}*/
				});
				//    ("背景图片:" + Constants.BadiDownImgUrl
				// + record_List_Models.get(position).getImage());
				myname.setText(record_List_Models.get(position).getNickName());
				// f_m_i_l_toupiao.setOnClickListener(new OnClickListener() {
				// @Override
				// public void onClick(View arg0) {
				// Toast.makeText(getActivity(), "投票", 0).show();
				// }
				// });

				if (record_List_Models.get(position).getIs_vote().equals("1")) {
					f_m_i_l_toupiao.setVisibility(View.VISIBLE);// 权限为可以投票
					votenumber.setVisibility(View.VISIBLE);
					if (record_List_Models.get(position).getVoted().equals("0")) {
						// 可投票
						f_m_i_l_toupiao
								.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View arg0) {
										if (!Utils.getUid(getActivity())
												.equals("")) {

											pos = position;
											vote(Utils.getUid(getActivity()),
													record_List_Models.get(
															position).getRid());
										} else {
											Toast.makeText(
													getActivity(),
													getResources().getString(
															R.string.l_xb10), 0)
													.show();
										}
									}
								});
					} else if (record_List_Models.get(position).getVoted()
							.equals("1")) {
						// 已经投了票了
						f_m_i_l_toupiao
								.setBackgroundResource(R.drawable.yuanpan_selector);
					}
				} else if (record_List_Models.get(position).getIs_vote()
						.equals("2")) {
					f_m_i_l_toupiao.setVisibility(View.GONE);// 权限为不可投票
					votenumber.setVisibility(View.GONE);
				}

			}

			return convertView;
		}
	}

	private void vote(final String uid, final String rid) {
		Utils.showPrgress(getActivity());
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("rid", rid);
				map.put("uid", uid);
//				   ("投票数据提交的是:" + map.toString());
				String content = Utils.sendRequest(map, Constants.BadiUrl
						+ "vote");
				if (content != null) {
//					   ("返回的投票数据是:" + content);
					results3 = Utils.checkResult_NNN(getActivity(), content);
					if (results3 != null
							&& !results3.getRetmsg().equals("null")) {
						handler.sendEmptyMessage(5);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	public void setOnRecordListGetViewOnClistener(SetGetView setgetView) {
		this.setGetView = setgetView;
	}

	public interface SetGetView {
		View setGetView(int position, View convertView, ViewGroup parent);
	}

	/**
	 * 用户+俱乐部 收藏的操作接口 提交方式GET
	 * 
	 * @param $uid
	 *            ;//收藏人的id
	 * @param $cid
	 *            ;//俱乐部收藏-------仅有record，humor_trends 这两种收藏方式，当为个人收藏时，值为0
	 * @param $nuid
	 *            ;//被收藏内容所属的用户id
	 * @param $nid
	 *            ;//被收藏的内容id
	 * @param $type
	 *            ;//被收藏的类型-----个人（3种）：photo_img，record，humor_trends
	 *            俱乐部（2种）：record，humor_trends
	 */
	public void collect(String cid, String nuid, String neirong_id, String type) {// Constants.BadiUrl+
																					// "praise_operate?uid="+uid+"&nid="+nid+"&nuid="+nuid+"&type="+type
		/*
		 * 用户收藏的操作接口 提交方式GET
		 * 
		 * @param $uid;//收藏人的id @param $nuid;//被收藏内容所属的用户id
		 * 
		 * @param $nid;//被收藏的内容id @param
		 * $type;//被收藏的类型（photo_img，record，humor_trends）
		 */
		String uid = Utils.getUid(getActivity());
		Utils.showPrgress(getActivity());
		CommonUtils.CommomGetfunction(getActivity(), Constants.BadiUrl
				+ "collect_operate?uid=" + uid + "&cid=" + cid + "&nuid="
				+ nuid + "&nid=" + neirong_id + "&type=" + type, handler, 1, 9,
				10, 11);
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		Page = 1;
		record_List_Models = new ArrayList<Record_List_Model>();
		All_record(Page);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		All_record(++Page);
	}
}
